package com.wangfugui.mybatisplus.controller;

import com.wangfugui.mybatisplus.common.CommonErrorCode;
import com.wangfugui.mybatisplus.common.Result;
import com.wangfugui.mybatisplus.common.exception.BusinessException;
import com.wangfugui.mybatisplus.common.utils.*;
import com.wangfugui.mybatisplus.service.OssService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.reflect.FieldUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;

@RestController
@RequestMapping("/oss")
@Api(tags = "OSS文件管理")
@Slf4j
public class OssController {

    @Autowired
    private OssService ossService;

    private static final String CWEBP_LINUX = "cwebp_win64";
    private static final String WEBP = "webp";

    private static final String SPOT = ".";

    @PostMapping("/upload")
    @ApiOperation("文件上传")
    public Result<String> upload(@RequestParam("file") MultipartFile file,
                                 @RequestParam(required = false) String dir) {
        // 1. 校验文件
        if (file.isEmpty()) {
            return Result.ofFail("请选择文件");
        }
        try {
            String filename = file.getOriginalFilename();
            File newFile = new File(filename);
            FileOutputStream os = new FileOutputStream(newFile);
            os.write(file.getBytes());
            os.close();
            file.transferTo(newFile);
            //上传到OSS
            String uploadUrl = AliyunOSSUtil.upload(newFile);
            // 同步到表
            return Result.ofSuccess(uploadUrl);
        } catch (Exception ex) {
        }
        return Result.ofSuccess(StringUtils.EMPTY);
    }


    @PostMapping("/uploadImageAsWebp")
    @ApiOperation("上传图片并转换为WebP格式")
    public Result<String> uploadImageAsWebp(
            @RequestParam("file") MultipartFile file,
            @RequestParam(defaultValue = "images") String dir,
            @RequestParam(defaultValue = "0.8") float quality) {

        InputStream inputStream = null;
        InputStream in = null;
        File fileObj = null;
        try {
            inputStream = file.getInputStream();
            String originalFilename = file.getOriginalFilename();

            // 控制文件大小在3M以内
            if (inputStream.available() > 3145728) {
                return Result.ofFail("图片不能大于3M");
            }
            // 生成临时目录
            String fileExt = FilenameUtils.getExtension(Optional.ofNullable(originalFilename).orElse(""));
            String tempDir = FilenameUtils.normalize(FileUtil.getTempDir("F:\\temp"), SystemUtil.isNotWindows());
            String newName = IdUtils.getId() + "." + fileExt;
            fileObj = new File(tempDir, FilenameUtils.normalize(newName, SystemUtil.isNotWindows()));
            file.transferTo(fileObj);

            // 输出目标是webp
            String outUrl = "F:\\temp" + File.separator + FileUtil.UuidFileName(WEBP);
            boolean webpResult = false;

            webpResult = WebpUtils.convertToWebp(fileObj.getPath(), outUrl, 80, "F:\\工作\\workspace\\liyu\\spring-boot-mybatisplus\\mybatisplus\\src\\main\\resources\\libwebp\\" + CWEBP_LINUX);

            if (webpResult) {
                log.info("webp image conversion successful, output file: {}", outUrl);
                boolean delete = fileObj.delete();
                if (!delete) {
                    throw new BusinessException(CommonErrorCode.BUSINESS_ERROR.getCode(),
                            "imageUpload file deletion failed!");
                }
                fileObj = new File(outUrl);
            } else {
                throw new BusinessException(CommonErrorCode.BUSINESS_ERROR.getCode(), "conversion failed!");
            }
            byte[] bytes = org.apache.commons.io.FileUtils.readFileToByteArray(fileObj);
            in = new ByteArrayInputStream(bytes);
            //上传到OSS
            String uploadUrl = AliyunOSSUtil.upload(new File(outUrl));

            return Result.ofSuccess(uploadUrl);
        } catch (IOException | NullPointerException e) {
            log.error("FileUploadController# imageUpload() error = {}", e.getMessage());
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    log.error("FileUploadController# inputStream. close() error = {}", e.getMessage());
                }
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        log.error("FileUploadController# inputStream. close() error = {}",
                                e.getMessage());
                    }
                }
            }

            if (fileObj != null) {
                // 这里需要在输出流关闭后删除临时文件，否则将出现“文件占用无法删除异常”
                FileUtil.delTempFile(fileObj.toPath());
            }

        }
        return null;
    }

}